<template>
  <div class="multi-param-analysis">
    <div class="analysis-container">
      <!-- 左侧筛选区 -->
      <div class="filter-panel">
        <div class="panel-header">
          <h3>筛选条件</h3>
          <el-button link @click="toggleFilterPanel">
            {{ filterCollapsed ? '展开' : '折叠' }}
          </el-button>
        </div>

        <el-collapse v-model="activeFilterItems">
          <!-- 设施筛选 -->
          <el-collapse-item name="facility" title="设施筛选">
            <div class="filter-group">
              <el-input v-model="facilityFilterText" placeholder="搜索设施" clearable size="small" />
              <el-tree ref="facilityTreeRef" :data="facilityTreeData" show-checkbox node-key="facilityId"
                :props="facilityTreeProps" :filter-node-method="filterFacilityNode" @check="onFacilityCheck" />
            </div>
          </el-collapse-item>

          <!-- 参数筛选 -->
          <el-collapse-item name="param" title="参数筛选">
            <div class="filter-group">
              <div class="param-type-filter">
                <el-checkbox-group v-model="selectedParamTypes" @change="onParamTypeChange">
                  <el-checkbox v-for="type in paramTypes" :key="type" :label="type">
                    {{ type }}
                  </el-checkbox>
                </el-checkbox-group>
                <div class="param-actions">
                  <el-button link @click="selectAllParams">全选</el-button>
                  <el-button link @click="reverseSelectParams">反选</el-button>
                </div>
              </div>
              <el-checkbox-group v-model="selectedParamIds" class="param-list">
                <div v-for="param in filteredParams" :key="param.paramId" class="param-item">
                  <el-checkbox :label="param.paramId">
                    {{ param.paramName }} ({{ param.paramUnit }})
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </el-collapse-item>

          <!-- 时间筛选 -->
          <el-collapse-item name="time" title="时间维度">
            <div class="filter-group">
              <div class="quick-time">
                <el-radio-group v-model="quickTimeType" @change="onQuickTimeChange">
                  <el-radio-button label="last24hours">近24小时</el-radio-button>
                  <el-radio-button label="today">今日</el-radio-button>
                  <el-radio-button label="yesterday">昨日</el-radio-button>
                  <el-radio-button label="last7days">近7天</el-radio-button>
                  <el-radio-button label="last30days">近30天</el-radio-button>
                </el-radio-group>
              </div>
              <div class="custom-time">
                <el-date-picker v-model="timeRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
                  end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="x" @change="onTimeRangeChange" />
              </div>
              <div class="time-granularity">
                <el-select v-model="timeGranularity" placeholder="时间粒度">
                  <el-option label="小时" value="hour" />
                  <el-option label="日" value="day" />
                  <el-option label="周" value="week" />
                  <el-option label="月" value="month" />
                </el-select>
              </div>
            </div>
          </el-collapse-item>

          <!-- 统计规则 -->
          <el-collapse-item name="stat" title="统计规则">
            <div class="filter-group">
              <div class="stat-type">
                <el-select v-model="statType" placeholder="统计方式">
                  <el-option label="平均值" value="avg" />
                  <el-option label="最大值" value="max" />
                  <el-option label="最小值" value="min" />
                  <el-option label="中位数" value="median" />
                </el-select>
              </div>
              <div class="threshold-setting">
                <div class="threshold-item">
                  <span>偏差阈值：</span>
                  <el-input-number v-model="deviationThreshold" :min="0" :max="100" :step="1"
                    controls-position="right" />
                  <span>%</span>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>

        <div class="filter-actions">
          <el-button type="primary" @click="handleSearch" :loading="loading">
            查询分析
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>

        <!-- 用户视图管理 -->
        <div class="user-views">
          <el-divider>我的视图</el-divider>
          <div class="view-actions">
            <el-button link @click="handleSaveView">保存当前视图</el-button>
          </div>
          <div class="view-list">
            <div v-for="view in userViews" :key="view.viewId" class="view-item" @click="loadUserView(view)">
              <span>{{ view.viewName }}</span>
              <el-button link type="danger" @click.stop="handleDeleteUserView(view.viewId)">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间主可视化区 -->
      <div class="visualization-panel">
        <div class="chart-header">
          <div class="chart-toolbar">
            <el-radio-group v-model="chartType" size="small">
              <el-radio-button label="line">折线图</el-radio-button>
              <el-radio-button label="bar">柱状图</el-radio-button>
              <el-radio-button label="scatter">散点图</el-radio-button>
            </el-radio-group>
            <div class="toolbar-actions">
              <el-button size="small" @click="toggleDualYAxis">
                {{ showDualYAxis ? '关闭双Y轴' : '开启双Y轴' }}
              </el-button>
              <el-button size="small" @click="exportChart">导出图表</el-button>
            </div>
          </div>
        </div>

        <div class="chart-container">
          <div v-if="tableData.length === 0 && !loading" class="empty-chart">
            <el-empty description="暂无数据，请选择筛选条件后点击查询分析" />
          </div>
          <div v-else ref="chartRef" class="chart"></div>
        </div>

        <!-- 异常点分布 -->
        <div class="abnormal-panel" v-if="abnormalData.length > 0">
          <h4>异常点分布</h4>
          <div ref="abnormalChartRef" class="abnormal-chart" style="width: 100%; height: 200px;"></div>
        </div>
      </div>
    </div>

    <!-- 底部数据详情区 -->
    <div class="data-panel">
      <div class="stat-cards">
        <el-row :gutter="20">
          <el-col :span="4" v-for="stat in statIndicators" :key="stat.key">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="data-table">
        <div class="table-header">
          <h3>数据详情</h3>
          <el-button @click="exportData" :disabled="tableData.length === 0">导出Excel</el-button>
        </div>
        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading" empty-text="暂无数据">
          <el-table-column prop="monitorTime" label="监测时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.monitorTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="facilityName" label="设施名称" width="120" />
          <el-table-column prop="paramName" label="参数名称" width="120" />
          <el-table-column prop="monitorValue" label="参数值" width="100">
            <template #default="{ row }">
              {{ row.monitorValue }} {{ row.paramUnit }}
            </template>
          </el-table-column>
          <el-table-column prop="deviationRate" label="偏差率" width="120">
            <template #default="{ row }">
              <span :class="getDeviationRateClass(row.deviationRate)">
                {{ row.deviationRate ? (row.deviationRate * 100).toFixed(2) + '%' : '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="dataStatus" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.dataStatus === 1 ? 'danger' : 'success'" size="small">
                {{ row.dataStatus === 1 ? '异常' : '正常' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="standardMin" label="标准范围" min-width="150">
            <template #default="{ row }">
              {{ row.standardMin }} - {{ row.standardMax }} {{ row.paramUnit }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button v-if="row.dataStatus === 1" link type="primary" @click="handleReportAbnormal(row)">
                异常上报
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 保存视图对话框 -->
    <el-dialog v-model="saveViewDialogVisible" title="保存视图" width="400px">
      <el-form :model="viewForm" label-width="80px">
        <el-form-item label="视图名称">
          <el-input v-model="viewForm.viewName" placeholder="请输入视图名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="saveViewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSaveView">保存</el-button>
      </template>
    </el-dialog>

    <!-- 异常上报对话框 -->
    <el-dialog v-model="abnormalReportDialogVisible" title="异常上报" width="500px">
      <el-form :model="abnormalForm" label-width="100px">
        <el-form-item label="异常时间">
          <span>{{ formatDate(abnormalForm.monitorTime) }}</span>
        </el-form-item>
        <el-form-item label="设施名称">
          <span>{{ abnormalForm.facilityName }}</span>
        </el-form-item>
        <el-form-item label="参数名称">
          <span>{{ abnormalForm.paramName }}</span>
        </el-form-item>
        <el-form-item label="异常值">
          <span>{{ abnormalForm.monitorValue }} {{ abnormalForm.paramUnit }}</span>
        </el-form-item>
        <el-form-item label="标准范围">
          <span>{{ abnormalForm.standardMin }} - {{ abnormalForm.standardMax }} {{ abnormalForm.paramUnit }}</span>
        </el-form-item>
        <el-form-item label="异常描述">
          <el-input v-model="abnormalForm.description" type="textarea" :rows="3" placeholder="请描述异常情况" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="abnormalReportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReportAbnormal">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getFacilities,
  getParams,
  multiParamAnalysis,
  getUserViews,
  saveUserView,
  deleteUserView
} from '@/api/prod_operate/prod_run/measurement_analysis'
import { formatDate, getQuickTimeRange } from '@/utils/date'

// 常量定义
const QUICK_TIME_OPTIONS = [
  { label: '近24小时', value: 'last24hours' },
  { label: '今日', value: 'today' },
  { label: '昨日', value: 'yesterday' },
  { label: '近7天', value: 'last7days' },
  { label: '近30天', value: 'last30days' }
]

const STAT_TYPE_OPTIONS = [
  { label: '平均值', value: 'avg' },
  { label: '最大值', value: 'max' },
  { label: '最小值', value: 'min' },
  { label: '中位数', value: 'median' }
]

const TIME_GRANULARITY_OPTIONS = [
  { label: '小时', value: 'hour' },
  { label: '日', value: 'day' },
  { label: '周', value: 'week' },
  { label: '月', value: 'month' }
]

const CHART_TYPE_OPTIONS = [
  { label: '折线图', value: 'line' },
  { label: '柱状图', value: 'bar' },
  { label: '散点图', value: 'scatter' }
]

const DEFAULT_DEVIATION_THRESHOLD = 10
const DEFAULT_QUICK_TIME = 'last24hours'
const DEFAULT_TIME_GRANULARITY = 'hour'
const DEFAULT_STAT_TYPE = 'avg'
const DEFAULT_CHART_TYPE = 'line'

// 响应式数据
const loading = ref(false)
const filterCollapsed = ref(false)
const activeFilterItems = ref(['facility', 'param', 'time', 'stat'])

// 设施筛选
const facilityTreeRef = ref()
const facilityFilterText = ref('')
const facilityTreeData = ref([])
const facilityTreeProps = {
  children: 'children',
  label: 'facilityName'
}
const selectedFacilityIds = ref([])

// 参数筛选
const paramTypes = ref([])
const selectedParamTypes = ref([])
const allParams = ref([])
const selectedParamIds = ref([])

// 使用 computed 优化参数过滤
const filteredParams = computed(() => {
  if (selectedParamTypes.value.length === 0) {
    return []
  }
  return allParams.value.filter(param =>
    selectedParamTypes.value.includes(param.paramType)
  )
})

// 时间筛选
const quickTimeType = ref(DEFAULT_QUICK_TIME)
const timeRange = ref([])
const timeGranularity = ref(DEFAULT_TIME_GRANULARITY)

// 统计规则
const statType = ref(DEFAULT_STAT_TYPE)
const deviationThreshold = ref(DEFAULT_DEVIATION_THRESHOLD)

// 图表相关
const chartRef = ref()
const abnormalChartRef = ref()
const chartType = ref(DEFAULT_CHART_TYPE)
const showDualYAxis = ref(false)
let chartInstance = null
let abnormalChartInstance = null
let resizeTimer = null

// 数据
const tableData = ref([])
const abnormalData = ref([])
const statIndicators = ref([])

// 用户视图
const userViews = ref([])
const saveViewDialogVisible = ref(false)
const viewForm = reactive({
  viewName: ''
})

// 异常上报
const abnormalReportDialogVisible = ref(false)
const abnormalForm = reactive({
  monitorTime: '',
  facilityName: '',
  paramName: '',
  monitorValue: '',
  paramUnit: '',
  standardMin: '',
  standardMax: '',
  description: ''
})

// 初始化
onMounted(() => {
  initData()
  initCharts()
  initTimeRange()
  loadUserViews()
})

// 初始化数据
const initData = async () => {
  try {
    await loadFacilities()
    await loadParams()
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

// 加载设施数据
const loadFacilities = async () => {
  try {
    const res = await getFacilities()
    if (res.success) {
      // 按工艺单元分组
      const processUnits = {}
      res.data.forEach(facility => {
        if (!processUnits[facility.processUnit]) {
          processUnits[facility.processUnit] = []
        }
        processUnits[facility.processUnit].push({
          facilityId: facility.facilityId,
          facilityName: facility.facilityName,
          processUnit: facility.processUnit
        })
      })

      facilityTreeData.value = Object.keys(processUnits).map(unit => ({
        facilityId: unit,
        facilityName: unit,
        children: processUnits[unit]
      }))
    }
  } catch (error) {
    console.error('加载设施数据失败:', error)
    ElMessage.error('加载设施数据失败')
  }
}

// 加载参数数据
const loadParams = async () => {
  try {
    const res = await getParams()
    if (res.success) {
      allParams.value = res.data
      paramTypes.value = res.paramTypes || []
      selectedParamTypes.value = [...(res.paramTypes || [])]
      // 默认选择水质类前3个参数
      const waterParams = res.data.filter(p => p.paramType === '水质').slice(0, 3)
      selectedParamIds.value = waterParams.map(p => p.paramId)
    }
  } catch (error) {
    console.error('加载参数数据失败:', error)
    ElMessage.error('加载参数数据失败')
  }
}

// 初始化时间范围
const initTimeRange = () => {
  const range = getQuickTimeRange(quickTimeType.value)
  timeRange.value = [range.startTime, range.endTime]
}

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    if (chartRef.value) {
      chartInstance = echarts.init(chartRef.value)
    }
    if (abnormalChartRef.value) {
      abnormalChartInstance = echarts.init(abnormalChartRef.value)
    }
    window.addEventListener('resize', handleResize)
  })
}

// 处理窗口大小变化（添加防抖优化）
const handleResize = () => {
  if (resizeTimer) {
    clearTimeout(resizeTimer)
  }
  resizeTimer = setTimeout(() => {
    chartInstance?.resize()
    abnormalChartInstance?.resize()
  }, 200)
}

// 设施筛选
const filterFacilityNode = (value, data) => {
  if (!value) return true
  return data.facilityName.includes(value)
}

const onFacilityCheck = () => {
  const checkedNodes = facilityTreeRef.value.getCheckedNodes()
  selectedFacilityIds.value = checkedNodes
    .filter(node => !node.children)
    .map(node => node.facilityId)
}

// 参数类型变化（已使用 computed，此函数可保留用于其他逻辑）
const onParamTypeChange = () => {
  // filteredParams 现在是 computed，会自动更新
  // 可以在这里添加其他逻辑，比如清空已选参数
  if (selectedParamTypes.value.length === 0) {
    selectedParamIds.value = []
  }
}

// 参数选择操作
const selectAllParams = () => {
  selectedParamIds.value = filteredParams.value.map(p => p.paramId)
}

const reverseSelectParams = () => {
  const allIds = filteredParams.value.map(p => p.paramId)
  selectedParamIds.value = allIds.filter(id => !selectedParamIds.value.includes(id))
}

// 时间筛选变化
const onQuickTimeChange = () => {
  initTimeRange()
}

const onTimeRangeChange = () => {
  quickTimeType.value = ''
}

// 查询分析
const handleSearch = async () => {
  // 验证筛选条件
  if (selectedFacilityIds.value.length === 0) {
    ElMessage.warning('请选择至少一个设施')
    return
  }
  if (selectedParamIds.value.length === 0) {
    ElMessage.warning('请选择至少一个参数')
    return
  }
  if (!timeRange.value || timeRange.value.length !== 2) {
    ElMessage.warning('请选择时间范围')
    return
  }

  // 验证时间范围合理性
  const [startTime, endTime] = timeRange.value
  if (startTime >= endTime) {
    ElMessage.warning('开始时间必须小于结束时间')
    return
  }

  // 检查时间范围是否过大（可选，根据业务需求调整）
  const timeDiff = endTime - startTime
  const maxTimeRange = 90 * 24 * 60 * 60 * 1000 // 90天
  if (timeDiff > maxTimeRange) {
    ElMessage.warning('时间范围不能超过90天，请缩小查询范围')
    return
  }

  loading.value = true
  try {
    const params = {
      facilityIds: selectedFacilityIds.value,
      paramIds: selectedParamIds.value,
      startTime: timeRange.value[0],
      endTime: timeRange.value[1],
      statType: statType.value,
      timeGranularity: timeGranularity.value
    }

    const res = await multiParamAnalysis(params)
    if (res.success) {
      tableData.value = res.data || []
      abnormalData.value = res.abnormalData || []
      updateStatIndicators(res.indicators || {})
      
      // 使用 nextTick 确保 DOM 更新后再渲染图表
      await nextTick()
      // 确保图表实例已初始化
      if (!chartInstance && chartRef.value) {
        chartInstance = echarts.init(chartRef.value)
      }
      if (tableData.value.length > 0) {
        renderChart(tableData.value)
      } else {
        // 清空图表
        chartInstance?.clear()
        abnormalChartInstance?.clear()
        ElMessage.info('未查询到数据')
      }
      
      if (abnormalData.value.length > 0) {
        await nextTick()
        // 确保异常图表实例已初始化
        if (!abnormalChartInstance && abnormalChartRef.value) {
          abnormalChartInstance = echarts.init(abnormalChartRef.value)
        }
        renderAbnormalChart(abnormalData.value)
      } else if (abnormalChartInstance) {
        abnormalChartInstance.clear()
      }
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error(error.message || '查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 更新统计指标
const updateStatIndicators = (indicators) => {
  // 计算最大偏差率
  let maxDeviationRate = 0
  if (tableData.value && tableData.value.length > 0) {
    tableData.value.forEach(item => {
      if (item.deviationRate && Math.abs(item.deviationRate) > maxDeviationRate) {
        maxDeviationRate = Math.abs(item.deviationRate)
      }
    })
  }

  statIndicators.value = [
    {
      key: 'avg',
      label: '参数平均值',
      value: indicators?.totalAverage ? indicators.totalAverage.toFixed(2) : '0'
    },
    {
      key: 'abnormal',
      label: '异常次数',
      value: indicators?.totalAbnormalCount || '0'
    },
    {
      key: 'deviation',
      label: '最大偏差率',
      value: maxDeviationRate > 0 ? (maxDeviationRate * 100).toFixed(2) + '%' : '0%'
    },
    {
      key: 'normalRate',
      label: '正常运行率',
      value: indicators?.normalRate ? indicators.normalRate.toFixed(2) + '%' : '100%'
    },
    {
      key: 'dataCount',
      label: '数据总量',
      value: indicators?.totalDataCount || '0'
    }
  ]
}

// 渲染主图表（优化性能）
const renderChart = (data) => {
  if (!data || data.length === 0) {
    return
  }
  
  // 如果图表实例不存在，先初始化
  if (!chartInstance) {
    nextTick(() => {
      if (chartRef.value) {
        chartInstance = echarts.init(chartRef.value)
        // 初始化后重新调用渲染
        renderChart(data)
        return
      }
    })
    return
  }

  try {
    // 数据处理：按设施和参数分组（优化算法）
    const seriesDataMap = new Map()
    const timeSet = new Set()

    // 第一遍遍历：收集所有时间点和系列
    data.forEach(item => {
      const timeKey = formatDate(item.monitorTime, 'MM-dd HH:mm')
      timeSet.add(timeKey)

      const seriesKey = `${item.facilityName}-${item.paramName}`
      if (!seriesDataMap.has(seriesKey)) {
        seriesDataMap.set(seriesKey, {
          name: seriesKey,
          type: chartType.value === 'bar' ? 'bar' : chartType.value === 'scatter' ? 'scatter' : 'line',
          data: [],
          smooth: chartType.value === 'line',
          symbol: chartType.value === 'scatter' ? 'circle' : 'none',
          symbolSize: chartType.value === 'scatter' ? 6 : undefined
        })
      }
    })

    const xAxisData = Array.from(timeSet).sort()

    // 第二遍遍历：填充数据（使用 Map 优化查找）
    const dataMap = new Map()
    data.forEach(item => {
      const timeKey = formatDate(item.monitorTime, 'MM-dd HH:mm')
      const seriesKey = `${item.facilityName}-${item.paramName}`
      const key = `${timeKey}-${seriesKey}`
      dataMap.set(key, item.monitorValue)
    })

    // 填充系列数据
    seriesDataMap.forEach((series, seriesKey) => {
      xAxisData.forEach(time => {
        const key = `${time}-${seriesKey}`
        series.data.push(dataMap.get(key) ?? null)
      })
    })

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function (params) {
          if (!params || params.length === 0) return ''
          let result = `<div style="margin-bottom: 4px;">${params[0].axisValue}</div>`
          params.forEach(param => {
            const value = param.value !== null && param.value !== undefined 
              ? typeof param.value === 'number' 
                ? param.value.toFixed(2) 
                : param.value 
              : '-'
            result += `<div style="margin: 2px 0;">
              <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${param.color};margin-right:5px;"></span>
              ${param.seriesName}: <strong>${value}</strong>
            </div>`
          })
          return result
        }
      },
      legend: {
        data: Array.from(seriesDataMap.keys()),
        type: 'scroll',
        bottom: 10,
        itemGap: 20
      },
      grid: {
        left: '3%',
        right: showDualYAxis.value ? '8%' : '4%',
        bottom: '15%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
        boundaryGap: chartType.value === 'bar',
        axisLabel: {
          rotate: xAxisData.length > 10 ? 45 : 0,
          interval: 'auto'
        }
      },
      yAxis: showDualYAxis.value ? [
        {
          type: 'value',
          name: '参数值',
          position: 'left'
        },
        {
          type: 'value',
          name: '偏差率',
          position: 'right'
        }
      ] : {
        type: 'value',
        name: '参数值'
      },
      dataZoom: xAxisData.length > 20 ? [
        {
          type: 'slider',
          start: 0,
          end: 100,
          height: 20,
          bottom: 5
        },
        {
          type: 'inside',
          start: 0,
          end: 100
        }
      ] : [],
      series: Array.from(seriesDataMap.values())
    }

    chartInstance.setOption(option, true)
  } catch (error) {
    console.error('渲染图表失败:', error)
    ElMessage.error('图表渲染失败')
  }
}

// 渲染异常图表
const renderAbnormalChart = (abnormalData) => {
  if (!abnormalData || abnormalData.length === 0) {
    return
  }
  
  // 如果图表实例不存在，先初始化
  if (!abnormalChartInstance) {
    nextTick(() => {
      if (abnormalChartRef.value) {
        abnormalChartInstance = echarts.init(abnormalChartRef.value)
        // 初始化后重新调用渲染
        renderAbnormalChart(abnormalData)
        return
      }
    })
    return
  }

  const facilityAbnormalCount = {}
  abnormalData.forEach(item => {
    if (!facilityAbnormalCount[item.facilityName]) {
      facilityAbnormalCount[item.facilityName] = 0
    }
    facilityAbnormalCount[item.facilityName]++
  })

  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '异常分布',
        type: 'pie',
        radius: '50%',
        data: Object.keys(facilityAbnormalCount).map(facility => ({
          value: facilityAbnormalCount[facility],
          name: facility
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  abnormalChartInstance.setOption(option)
}

// 重置筛选条件
const handleReset = () => {
  facilityTreeRef.value?.setCheckedKeys([])
  selectedFacilityIds.value = []
  selectedParamTypes.value = [...paramTypes.value]
  const waterParams = allParams.value
    .filter(p => p.paramType === '水质')
    .slice(0, 3)
  selectedParamIds.value = waterParams.map(p => p.paramId)
  quickTimeType.value = DEFAULT_QUICK_TIME
  initTimeRange()
  timeGranularity.value = DEFAULT_TIME_GRANULARITY
  statType.value = DEFAULT_STAT_TYPE
  deviationThreshold.value = DEFAULT_DEVIATION_THRESHOLD
  // 清空数据
  tableData.value = []
  abnormalData.value = []
  statIndicators.value = []
  if (chartInstance) {
    chartInstance.clear()
  }
  if (abnormalChartInstance) {
    abnormalChartInstance.clear()
  }
}

// 切换筛选面板
const toggleFilterPanel = () => {
  filterCollapsed.value = !filterCollapsed.value
  if (filterCollapsed.value) {
    activeFilterItems.value = []
  } else {
    activeFilterItems.value = ['facility', 'param', 'time', 'stat']
  }
}

// 切换双Y轴
const toggleDualYAxis = () => {
  showDualYAxis.value = !showDualYAxis.value
  // 重新渲染图表
  if (tableData.value.length > 0) {
    renderChart(tableData.value)
  }
}

// 导出功能
const exportChart = () => {
  if (!chartInstance) {
    ElMessage.warning('暂无图表可导出')
    return
  }
  try {
    const chartDataURL = chartInstance.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.href = chartDataURL
    const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
    link.download = `监测分析图表-${timestamp}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('图表导出成功')
  } catch (error) {
    console.error('导出图表失败:', error)
    ElMessage.error('导出图表失败')
  }
}

const exportData = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }
  // TODO: 实现 Excel 导出功能
  ElMessage.info('导出功能开发中')
}

// 偏差率样式
const getDeviationRateClass = (deviationRate) => {
  if (!deviationRate) return ''
  const absRate = Math.abs(deviationRate)
  if (absRate > 0.1) return 'deviation-high'
  if (absRate > 0.05) return 'deviation-medium'
  return 'deviation-low'
}

// 异常上报
const handleReportAbnormal = (row) => {
  Object.assign(abnormalForm, {
    monitorTime: row.monitorTime,
    facilityName: row.facilityName,
    paramName: row.paramName,
    monitorValue: row.monitorValue,
    paramUnit: row.paramUnit,
    standardMin: row.standardMin,
    standardMax: row.standardMax,
    description: ''
  })
  abnormalReportDialogVisible.value = true
}

const confirmReportAbnormal = () => {
  ElMessage.success('异常上报成功')
  abnormalReportDialogVisible.value = false
}

// 用户视图管理
const loadUserViews = async () => {
  try {
    const res = await getUserViews('user001', 'multi_param')
    if (res.success) {
      userViews.value = res.data
    }
  } catch (error) {
    console.error('加载用户视图失败:', error)
  }
}

const handleSaveView = () => {
  viewForm.viewName = ''
  saveViewDialogVisible.value = true
}

const confirmSaveView = async () => {
  if (!viewForm.viewName.trim()) {
    ElMessage.warning('请输入视图名称')
    return
  }

  try {
    const viewData = {
      userId: 'user001',
      viewName: viewForm.viewName,
      pageType: 'multi_param',
      chartType: chartType.value,
      filterCondition: JSON.stringify({
        facilityIds: selectedFacilityIds.value,
        paramIds: selectedParamIds.value,
        timeRange: timeRange.value,
        statType: statType.value
      })
    }

    const res = await saveUserView(viewData)
    if (res.success) {
      ElMessage.success('视图保存成功')
      saveViewDialogVisible.value = false
      loadUserViews()
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const loadUserView = (view) => {
  try {
    const filterCondition = JSON.parse(view.filterCondition)
    selectedFacilityIds.value = filterCondition.facilityIds
    selectedParamIds.value = filterCondition.paramIds
    timeRange.value = filterCondition.timeRange
    statType.value = filterCondition.statType
    chartType.value = view.chartType

    // 设置树形选择
    nextTick(() => {
      if (facilityTreeRef.value) {
        facilityTreeRef.value.setCheckedKeys(filterCondition.facilityIds)
      }
    })

    ElMessage.success('视图加载成功')
  } catch (error) {
    ElMessage.error('视图加载失败')
  }
}

const handleDeleteUserView = async (viewId) => {
  try {
    await ElMessageBox.confirm('确定删除该视图吗？', '提示', {
      type: 'warning'
    })

    const res = await deleteUserView(viewId)
    if (res.success) {
      ElMessage.success('删除成功')
      loadUserViews()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 监听图表类型变化
watch(chartType, () => {
  if (tableData.value.length > 0) {
    renderChart(tableData.value)
  }
})

// 监听设施筛选文本
watch(facilityFilterText, (val) => {
  facilityTreeRef.value?.filter(val)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (resizeTimer) {
    clearTimeout(resizeTimer)
  }
  chartInstance?.dispose()
  abnormalChartInstance?.dispose()
  chartInstance = null
  abnormalChartInstance = null
})
</script>

<style scoped>
.multi-param-analysis {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: visible;
}

.analysis-container {
  flex: 1;
  display: flex;
  min-height: 0;
  overflow: visible;
  max-height: calc(100vh - 100px);
}

.filter-panel {
  width: 300px;
  background: #f8f9fa;
  padding: 16px;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
  flex-shrink: 0;
  max-height: calc(100vh - 100px);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.filter-group {
  padding: 8px 0;
}

.param-type-filter {
  margin-bottom: 12px;
}

.param-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.param-list {
  max-height: 200px;
  overflow-y: auto;
}

.param-item {
  margin-bottom: 8px;
}

.quick-time {
  margin-bottom: 12px;
}

.custom-time,
.time-granularity,
.stat-type,
.threshold-setting {
  margin-bottom: 12px;
}

.threshold-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-actions {
  margin-top: 16px;
  display: flex;
  gap: 8px;
}

.user-views {
  margin-top: 20px;
}

.view-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
}

.view-item:hover {
  background: #e6f7ff;
}

.visualization-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  min-height: 0;
  overflow-y: auto;
}

.chart-header {
  margin-bottom: 16px;
}

.chart-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  flex: 0 0 400px;
  position: relative;
  margin-bottom: 16px;
}

.chart {
  width: 100%;
  height: 400px;
}

.empty-chart {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400px;
  background: #fafafa;
  border-radius: 4px;
}

.abnormal-panel {
  margin-top: 20px;
  border-top: 1px solid #e4e7ed;
  padding-top: 16px;
}

.data-panel {
  border-top: 1px solid #e4e7ed;
  padding: 16px;
  background: #fafafa;
  flex-shrink: 0;
  max-height: 50vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.data-panel .el-table {
  flex: 1;
  overflow-y: auto;
}

.stat-cards {
  margin-bottom: 16px;
}

.stat-card {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.data-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-shrink: 0;
}

.deviation-high {
  color: #f56c6c;
  font-weight: bold;
}

.deviation-medium {
  color: #e6a23c;
}

.deviation-low {
  color: #67c23a;
}

/* 优化滚动条样式 */
.filter-panel::-webkit-scrollbar,
.param-list::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.filter-panel::-webkit-scrollbar-track,
.param-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.filter-panel::-webkit-scrollbar-thumb,
.param-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.filter-panel::-webkit-scrollbar-thumb:hover,
.param-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式优化 */
@media (max-width: 1200px) {
  .analysis-container {
    flex-direction: column;
  }

  .filter-panel {
    width: 100%;
    max-height: 400px;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }
}
</style>